﻿using System;
using System.Text;
using Microsoft.Practices.RecipeFramework;
using EnvDTE;
using System.IO;
using System.Xml;
using System.Reflection;
using System.Security.Cryptography;
using System.Collections;
using System.Diagnostics;
using Microsoft.Practices.RecipeFramework.Library;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework.Services;

namespace SteriaMummert.SharePoint.SoftwareFactoryLite.ValueProviders
{
    [ServiceDependency(typeof(DTE))]
    public class AssemblyProvider : ValueProvider
    {
        protected string GetBasePath()
        {
            return base.GetService<IConfigurationService>(true).BasePath;
        }

        public override bool OnBeginRecipe(object currentValue, out object newValue)
        {
            string snPath = GetBasePath() + "\\sn.exe";

            try
            {
                string assemblyfullname = "";

                //get key filename of the current selected project
                string keyfilename = "";
                DTE service = (DTE)this.GetService(typeof(DTE));
                if (service.SelectedItems.Count > 0)
                {
                    try
                    {
                        SelectedItem item = service.SelectedItems.Item(1);
                        Project p = item.Project;
                        keyfilename = Path.GetDirectoryName(p.FullName) + "\\" + p.Properties.Item("AssemblyOriginatorKeyFile").Value;
                        if (!File.Exists(keyfilename))
                        {
                            //file is stored on solution level
                            keyfilename = Path.GetDirectoryName(p.DTE.Solution.FileName) + "\\" + p.Properties.Item("AssemblyOriginatorKeyFile").Value;
                        }

                        //fdsa.fdsfad.fdsafdas, Version=1.0.0.0, Culture=neutral, PublicKeyToken=80b59a59cf67db9f
                        assemblyfullname = p.Properties.Item("AssemblyName").Value + ", Version=" + p.Properties.Item("AssemblyVersion").Value + ", Culture=neutral, PublicKeyToken=";
                    }
                    catch (Exception ex)
                    {
                    }
                }

                if (!File.Exists(keyfilename))
                {
                    throw new FileNotFoundException("The key file could not be found " + keyfilename);
                }

                string publickeyfilepath = Path.GetTempFileName();

                //extract public key into temp file
                ProcessStartInfo startInfo = new ProcessStartInfo(snPath, string.Format("-p \"{0}\" \"{1}\"", keyfilename, publickeyfilepath));
                startInfo.CreateNoWindow = true;
                startInfo.UseShellExecute = false;
                System.Diagnostics.Process snProcess = System.Diagnostics.Process.Start(startInfo);
                snProcess.WaitForExit(10000);

                //Get public key token from temp fie
                ProcessStartInfo startInfo2 = new ProcessStartInfo(snPath, string.Format("-t \"{0}\"", publickeyfilepath));
                startInfo2.CreateNoWindow = true;
                startInfo2.UseShellExecute = false;
                startInfo2.RedirectStandardOutput = true;
                System.Diagnostics.Process snProcess2 = System.Diagnostics.Process.Start(startInfo2);
                string output = snProcess2.StandardOutput.ReadToEnd();
                snProcess2.WaitForExit(10000);

                string z = output;

                //output looks like
                //"\r\nMicrosoft (R) .NET Framework Strong Name Utility  Version 2.0.50727.42\r\nCopyright (c) Microsoft Corporation.  All rights reserved.\r\n\r\nPublic key token is 80b59a59cf67db9f\r\n"
                string key = output.Substring(output.IndexOf("Public key token is") + 20, 16);

                assemblyfullname += key;

                newValue = assemblyfullname;
                return true;
            }
            catch (Exception)
            {
            }

            newValue = "";
            return true;
        }
    }
}

